/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-03-13     78677       the first version
 */

#include "main.h"
// 宏定义

// 函数定义
static void Led_TimerCallback(void *parameter);
static void Timer1_ISR(int vector, void *param);

// 变量定义
static
int8_t flag = 0;

static void Led_TimerCallback(void *parameter){
    RGB_Blue(~flag);
    flag = ~flag;
}

/*
 * 软件定时器
 */
rt_timer_t Timer_Init(void){
    return rt_timer_create("led", Led_TimerCallback, RT_NULL, 1000, RT_TIMER_FLAG_PERIODIC);  //创建一个周期定时器
}


int Timer_Start(void){
    RGB_Init();
    rt_timer_t timer = Timer_Init();
    rt_timer_start(timer);
    return 0;
}
//INIT_APP_EXPORT(Timer_Start);




void Timer1_ISR(int vector, void *param){
//    TMR1CPND = BIT(9);  //  清除中断标志位
//    RGB_Blue(~flag);
//    flag = ~flag;
    rt_kprintf("this is hwtimer timeout callback fucntion!\n");
        rt_kprintf("tick is :%d !\n", rt_tick_get());
}


int Timer1_Init(void){
    RGB_Init();
    TMR1CON = BIT(7);   // 开启tim1的溢出中断
    TMR1CNT = 0;        // 计时器清零
    TMR1PR  = (uint32_t)(get_sysclk_nhz()/RT_TICK_PER_SECOND - 1UL);       //1ms interrupt
    rt_hw_interrupt_install(IRQ_TMR1_VECTOR, Timer1_ISR, RT_NULL, "timer1");
    return 0;
}


rt_device_t hw_dev;         //设备句柄
rt_hwtimer_mode_t mode;     //控制参数，单次定时OR周期定时
rt_hwtimerval_t timeout_t;  //定时器超出值

/* 定时器超时回调函数 */
rt_err_t timeout_cb(rt_device_t dev, rt_size_t size)
{
    rt_kprintf("this is hwtimer timeout callback fucntion!\n");
    return 0;
}

int hw_sample(void)
{
    rt_err_t ret = RT_EOK;
    /* 查找设备 */
    hw_dev = rt_device_find("timer1");
    if(hw_dev == RT_NULL)
    {
        rt_kprintf("find %s failed\t\n", "timer1");
        return RT_ERROR;
    }
    /* 查找设备成功 */
    rt_kprintf("find %s success \t\n","timer1");

    /* 以读写的方式打开设备 */
    rt_device_open(hw_dev, RT_DEVICE_OFLAG_RDWR);

    /* 设置定时器工作模式为周期定时 */
    mode = HWTIMER_MODE_PERIOD;
    rt_device_control(hw_dev, HWTIMER_CTRL_MODE_SET, &mode);

    /* 超值回调函数 */
    rt_device_set_rx_indicate(hw_dev, timeout_cb);

    /* 配置超时值 */
    timeout_t.sec = 5;
    timeout_t.usec = 0;
    rt_device_write(hw_dev, 0, &timeout_t, sizeof(timeout_t));

    return RT_EOK;
}

//INIT_APP_EXPORT(hw_sample);







